package com.chushouya.controller.common;

import com.chushouya.common.annotations.AuthSkip;
import com.chushouya.common.util.RabbitMQUtil;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.rabbitmq.sender.AlipayFlowMessageSender;
import com.chushouya.order.service.api.SuhuishouOrderApiService;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Dates;
import com.general.framework.core.schema.Response;
import com.chushouya.common.constant.ServiceType;
import com.chushouya.common.constant.RabbitMqQueueEnum;
import com.chushouya.order.rabbitmq.sender.NotifyMessageSender;
import com.chushouya.order.service.admin.OrderNotifyService;
import com.chushouya.order.service.common.ManageDayStatTaskService;
import com.chushouya.product.service.api.ResolveEvaluateApiService;
import com.chushouya.product.service.common.ProductImageGenerateService;
import com.chushouya.product.dao.entity.ProductEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Api(tags = ServiceType.COMMON + "Mock测试")
@RestController
@RequestMapping(ServiceType.COMMON + "/mock")
@Slf4j
public class MockController {

    @Resource
    private RabbitMQUtil rabbitMQUtil;

    @Resource
    private OrderRepository orderRepository;

    @Resource
    private OrderNotifyService orderNotifyService;

    @Resource
    private ResolveEvaluateApiService resolveEvaluateApiService;

    @Resource
    private NotifyMessageSender notifyMessageSender;

    @Resource
    private ManageDayStatTaskService manageDayStatTaskService;

    @Resource
    private AlipayFlowMessageSender alipayFlowMessageSender;

    @Resource
    private SuhuishouOrderApiService suhuishouOrderApiService;

    @Resource
    private ProductImageGenerateService productImageGenerateService;

    @GetMapping("/test")
    public Response<String> test() {
        return Response.success("test");
    }

    @AuthSkip
    @ApiOperation("测试产品列表图片生成")
    @GetMapping("/testProductImage")
    public Response<String> testProductImage(Long categoryId, Long brandId, String title) {
        try {
            log.info("开始测试产品列表图片生成, categoryId: {}, brandId: {}, title: {}", categoryId, brandId, title);

            
            // 设置默认标题
            if (title == null || title.trim().isEmpty()) {
                title = "出手鸭产品回收最新行情";
            }
            
            // 查询产品列表
            List<ProductEntity> products = productImageGenerateService.getProductListByCategoryAndBrand(categoryId, brandId);
            
            if (products == null || products.isEmpty()) {
                log.warn("未查询到产品数据, categoryId: {}, brandId: {}", categoryId, brandId);
                throw Ex.business("未查询到产品数据");
            }
            
            log.info("查询到产品数量: {}", products.size());
            
            // 生成日期字符串
            String dateStr = new SimpleDateFormat("MM月dd日").format(new Date());
            
            // 尝试上传到OSS，如果失败则保存到本地
            String imageUrl = null;
            File localFile = null;
            
            try {
                // 先尝试上传到OSS
                imageUrl = productImageGenerateService.generateAndUploadProductListImage(products, title, dateStr, categoryId, brandId);
                if (imageUrl != null && !imageUrl.isEmpty()) {
                    log.info("产品列表图片上传OSS成功: {}", imageUrl);
                    return Response.success("图片生成并上传OSS成功！\n" +
                            "产品数量: " + products.size() + "\n" +
                            "OSS地址: " + imageUrl);
                }
            } catch (Exception ossException) {
                log.warn("OSS上传失败，降级到本地保存: {}", ossException.getMessage());
                // OSS上传失败，降级到本地保存
            }
            
            throw Ex.business("产品列表图片生成失败");
            
        } catch (Exception e) {
            log.error("测试产品列表图片生成失败", e);
            throw Ex.business("测试产品列表图片生成失败: " + e.getMessage());
        }
    }

    @AuthSkip
    @ApiOperation("测试产品列表图片生成并上传OSS")
    @GetMapping("/testProductImageOss")
    public Response<String> testProductImageOss(Long categoryId, Long brandId, String title) {
        try {
            log.info("开始测试产品列表图片生成并上传OSS, categoryId: {}, brandId: {}, title: {}", categoryId, brandId, title);
            
            // 设置默认标题
            if (title == null || title.trim().isEmpty()) {
                title = "出手鸭产品回收最新行情";
            }
            
            // 查询产品列表
            List<ProductEntity> products = productImageGenerateService.getProductListByCategoryAndBrand(categoryId, brandId);
            
            if (products == null || products.isEmpty()) {
                log.warn("未查询到产品数据, categoryId: {}, brandId: {}", categoryId, brandId);
                throw Ex.business("未查询到产品数据");
            }
            
            log.info("查询到产品数量: {}", products.size());
            
            // 生成日期字符串
            String dateStr = new SimpleDateFormat("MM月dd日").format(new Date());
            
            // 生成图片并上传到OSS
            String ossUrl = productImageGenerateService.generateAndUploadProductListImage(products, title, dateStr, categoryId, brandId);
            
            if (ossUrl != null && !ossUrl.isEmpty()) {
                log.info("产品列表图片上传OSS成功: {}", ossUrl);
                return Response.success("图片生成并上传OSS成功！\n" +
                        "产品数量: " + products.size() + "\n" +
                        "OSS地址: " + ossUrl);
            } else {
                log.error("产品列表图片上传OSS失败");
                throw Ex.business("产品列表图片上传OSS失败");
            }
            
        } catch (Exception e) {
            log.error("测试产品列表图片生成并上传OSS失败", e);
            throw Ex.business("测试产品列表图片生成并上传OSS失败: " + e.getMessage());
        }
    }

    @AuthSkip
    @ApiOperation("批量生成指定分类下所有品牌的产品图片")
    @GetMapping("/testBatchProductImageByCategory")
    public Response<String> testBatchProductImageByCategory(Long categoryId, String title) {
        try {
            log.info("开始批量生成分类下所有品牌产品图片, categoryId: {}, title: {}", categoryId, title);
            
            if (categoryId == null) {
                throw Ex.business("分类ID不能为空");
            }
            
            // 批量生成该分类下所有品牌的产品图片
            String result = productImageGenerateService.generateAllBrandImagesForCategory(categoryId, title);
            
            log.info("批量生成完成，结果: {}", result);
            return Response.success(result);
            
        } catch (Exception e) {
            log.error("批量生成产品图片失败", e);
            throw Ex.business("批量生成产品图片失败: " + e.getMessage());
        }
    }

    @ApiOperation("获取创建订单信息")
    @PostMapping("/getOrderCreate")
    @AuthSkip
    public Response<String> getOrderCreate(Long orderId) {
        // 1. 发送普通消息
//        rabbitMQUtil.sendMessage("chushouya.order.created", orderId);
//        // 2. 发送带类型的消息
//        RabbitMQUsageExample.OrderCreatedEvent event = new RabbitMQUsageExample.OrderCreatedEvent(orderId, "PENDING");
//        rabbitMQUtil.sendMessage("chushouya.order.created", "ORDER_CREATED", event);

        // 3. 发送延时消息 - 30分钟后检查订单状态
//        rabbitMQUtil.sendDelayMessage("chushouya.order.created", orderId, 2, TimeUnit.SECONDS);

//        rabbitMQUtil.sendMessage(RabbitMqQueueEnum.BONUS_VERIFICATION.getQueueName(), orderId);
        rabbitMQUtil.sendDelayMessage(RabbitMqQueueEnum.SUHUISHOU_ORDER_CREATE.getQueueName(), orderId,5L,TimeUnit.SECONDS);
        return Response.success();
    }

    @AuthSkip
    @ApiOperation("获取派单")
    @PostMapping("/getDispatch")
    public Response<String> getDispatch(Long orderId) {
        orderNotifyService.sendWechatToClerk(orderId);
        return Response.success();
    }

    @AuthSkip
    @ApiOperation("获取估价选项")
    @GetMapping("/getEvaluateItem")
    public Response<String> getEvaluateItem(Long productId) {
        log.info("evaluateItemId: {}", productId);
        resolveEvaluateApiService.resolveEvaluateItem(productId);
        return Response.success();
    }

    @AuthSkip
    @ApiOperation("测试速回收下单")
    @GetMapping("/getOrderSubmit")
    public Response<String> getOrderSubmit(Long orderId) {
        log.info("orderId: {}", orderId);
//        OrderEntity orderEntity =orderRepository.selectByPrimaryKey(orderId);
//        alipayFlowMessageSender.sendAlipayFlowMessage(orderEntity);
        rabbitMQUtil.sendDelayMessage(RabbitMqQueueEnum.SUHUISHOU_ORDER_CREATE.getQueueName(), orderId,5L, TimeUnit.SECONDS);

        return Response.success();
    }

    @AuthSkip
    @ApiOperation("测试推送")
    @GetMapping("/testPush")
    public Response<String> testPush(Long orderId, String notifyType, String remark) {
//        notifyMessageSender.sendPartnerOrderStatusNotifyMessage(orderId, notifyType, remark);
//        alipaySubscribeService.sendOrderSuccessNotify(orderId);RECYCLE_CANCEL PAYMENT_RECEIVED
        notifyMessageSender.sendAlipaySubscribeMessage(orderId, "MP-ALIPAY", "PAYMENT_RECEIVED");
        return Response.success();
    }

    @AuthSkip
    @ApiOperation("测试统计")
    @GetMapping("/testStat")
    public Response<String> testStat() {
        //遍历获取一个月的数据
        Date today = Dates.getFirstTime(new Date());
        Date startDate = Dates.getFirstTime(Dates.addMonths(today, -1));
        
        log.info("开始统计一个月的数据，从 {} 到 {}", startDate, today);
        
        Date currentDate = startDate;
        int count = 0;
        
        while (!currentDate.after(today)) {
            try {
                log.info("正在统计日期: {}", currentDate);
                manageDayStatTaskService.manageTodayStat(currentDate);
                count++;
                
                // 避免过于频繁的调用，稍作延迟
                Thread.sleep(100);
            } catch (Exception e) {
                log.error("统计日期 {} 时发生错误: {}", currentDate, e.getMessage(), e);
            }
            
            currentDate = Dates.addDays(currentDate, 1);
        }
        
        log.info("统计完成，共处理了 {} 天的数据", count);
        return Response.success("统计完成，共处理了 " + count + " 天的数据");
    }

}
